//
//  OBV.m
//  AppFinance
//
//  Created by wei on 12-7-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AFKpiOBV.h"

@implementation AFKpiOBV

static AFKpiOBV *_kpiOBV = nil;

static float _kpiMaxObv = 0;
static float _kpiMinObv = 0;

static float _kpiLastObv = 0;

+(AFKpiOBV*) app{
    if (_kpiOBV == nil) {
        _kpiOBV = [[self alloc] init];
    }
    return _kpiOBV;
}

+(float) kpiMaxObv{
    return _kpiMaxObv;
}
+(float) kpiMinObv{
    return _kpiMinObv;
}

+(float) kpiLastObv{
    return _kpiLastObv;
}

int obv_iParam[] = {12};

-(void) initKlineArray:(NSArray *)_kLineArray{
    kLineArray = _kLineArray;
    
    _kpiMaxObv = -100000000;
    _kpiMinObv = 100000000;
    
    _obvArray = nil;
}

-(void) obvData:(int) day{
    if(nil == kLineArray || [kLineArray count] <= 0){
        return;
    }
    int n = day;
    if(n > [kLineArray count] || n < 1 || (n + n) - 2 >= [kLineArray count]){
        return;
    }
    
    // OBV
    _obvArray = [NSMutableArray array];
    
    NSDictionary *dict;
    float pre_close = 0;
    float close = 0;
    float volume = 0;
    
    [_obvArray addObject:[NSNumber numberWithFloat:0]];
    dict = [kLineArray objectAtIndex:0];
    pre_close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
    volume = [[dict objectForKey:AF_K_MARKET_VOLUME] floatValue];
    
    float total = pre_close * volume;
    
    int _kLineCount = (int)[kLineArray count];
    
    float _pre_obv = 0;
    float _obv = 0;
    for(int i = 1; i < _kLineCount; i++){
        dict = [kLineArray objectAtIndex:i];
        close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
        volume = [[dict objectForKey:AF_K_MARKET_VOLUME] floatValue];
        
        if (volume == 0) {
            continue;
        }
        
        total += (close * volume);
        
        if(close > pre_close){
            _obv = _pre_obv + (float)(total / 1000.0f);
        }
        else{
            if(close < pre_close){
                _obv = _pre_obv - (float)(total / 1000.0f);
            }
            else{
                _obv = _pre_obv;
            }
        }
        
        [_obvArray addObject:[NSNumber numberWithFloat:_obv]];
        
        pre_close = close;
        _pre_obv = _obv;
        
        if (_kpiMaxObv < _obv) {
            _kpiMaxObv = _obv;
        }
        if (_kpiMinObv > _obv) {
            _kpiMinObv = _obv;
        }
    }
}

-(NSMutableArray *) kObvArray{
    return _obvArray;
}
@end
